"""
汽车之家数据分析系统 - 主窗口
现代化设计风格的汽车数据展示系统
"""

import sys
from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QPushButton, QLabel, QComboBox, QSpinBox,
                             QScrollArea, QProgressBar, QStatusBar, QMenuBar,
                             QAction, QMessageBox, QTabWidget, QGroupBox,
                             QTableWidget, QTableWidgetItem, QHeaderView,
                             QTextEdit, QFrame, QSizePolicy, QGridLayout,
                             QLineEdit, QFileDialog, QDialog)
from crawler.car_crawler import CarCrawler, CarInfo
from ui.car_widget import CarListWidget, CarWidget
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QTimer, QPropertyAnimation, QEasingCurve
from PyQt5.QtGui import QFont, QIcon, QPixmap, QPalette, QColor, QLinearGradient

# AI功能导入
try:
    from ui.ai_chat_widget import AIChatWidget
    AI_AVAILABLE = True
except ImportError:
    AI_AVAILABLE = False


class CarDetailDialog(QDialog):
    """汽车详情对话框"""

    def __init__(self, car_data, parent=None):
        super().__init__(parent)
        self.car_data = car_data
        self.setup_ui()
        self.setup_style()

    def setup_ui(self):
        """设置UI"""
        self.setWindowTitle("🚗 汽车详细信息")
        self.setFixedSize(700, 500)  # 增大对话框尺寸以容纳图片
        self.setModal(True)

        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(20)

        # 标题区域
        title_layout = QHBoxLayout()

        # 排名标签
        rank_label = QLabel(f"#{self.car_data.get('rank', 0)}")
        rank_label.setFont(QFont("Microsoft YaHei", 20, QFont.Bold))
        rank_label.setStyleSheet("""
            QLabel {
                color: white;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #ff6b6b, stop:1 #ee5a52);
                border-radius: 20px;
                padding: 10px 15px;
                min-width: 60px;
            }
        """)
        rank_label.setAlignment(Qt.AlignCenter)
        title_layout.addWidget(rank_label)

        # 车名
        name_label = QLabel(self.car_data.get('name', '未知车型'))
        name_label.setFont(QFont("Microsoft YaHei", 18, QFont.Bold))
        name_label.setStyleSheet("color: #2c3e50; margin-left: 15px;")
        title_layout.addWidget(name_label)
        title_layout.addStretch()

        main_layout.addLayout(title_layout)

        # 内容区域（图片 + 信息）
        content_layout = QHBoxLayout()

        # 左侧：汽车图片
        self.image_label = QLabel()
        self.image_label.setFixedSize(200, 150)
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setStyleSheet("""
            QLabel {
                border: 2px solid #e0e6ed;
                border-radius: 12px;
                background-color: white;
                padding: 10px;
            }
        """)
        self.image_label.setText("🚗\n加载中...")
        content_layout.addWidget(self.image_label)

        # 加载汽车图片
        self.load_car_image()

        # 右侧：详细信息区域
        info_frame = QFrame()
        info_frame.setStyleSheet("""
            QFrame {
                background-color: #f8f9fa;
                border-radius: 12px;
                padding: 20px;
            }
        """)
        info_layout = QVBoxLayout(info_frame)
        info_layout.setSpacing(15)

        # 评分信息
        score_layout = self.create_info_row("⭐ 评分", f"{self.car_data.get('score', 0):.1f} 分", "#f39c12")
        info_layout.addLayout(score_layout)

        # 价格信息
        price_layout = self.create_info_row("💰 价格", self.car_data.get('price', '暂无报价'), "#27ae60")
        info_layout.addLayout(price_layout)

        # 销量信息
        sales = self.car_data.get('sales', 0)
        sales_text = f"{sales:,} 辆"
        if sales > 30000:
            sales_text += " 🔥🔥🔥 (超热门)"
        elif sales > 20000:
            sales_text += " 🔥🔥 (热门)"
        elif sales > 10000:
            sales_text += " 🔥 (受欢迎)"

        sales_layout = self.create_info_row("📈 销量", sales_text, "#8e44ad")
        info_layout.addLayout(sales_layout)

        # 详情链接
        if self.car_data.get('detail_url'):
            url_layout = self.create_info_row("🔗 详情链接", "点击访问官方页面", "#3498db")
            info_layout.addLayout(url_layout)

        content_layout.addWidget(info_frame)
        main_layout.addLayout(content_layout)

        # 按钮区域
        button_layout = QHBoxLayout()

        # 访问官网按钮
        if self.car_data.get('detail_url'):
            visit_btn = QPushButton("🌐 访问官网")
            visit_btn.setFont(QFont("Microsoft YaHei", 12, QFont.Bold))
            visit_btn.setStyleSheet("""
                QPushButton {
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 #4facfe, stop:1 #00f2fe);
                    color: white;
                    border: none;
                    border-radius: 8px;
                    padding: 12px 20px;
                    font-weight: bold;
                }
                QPushButton:hover {
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 #43a3f5, stop:1 #00d4e6);
                }
            """)
            visit_btn.clicked.connect(self.visit_website)
            button_layout.addWidget(visit_btn)

        # 关闭按钮
        close_btn = QPushButton("❌ 关闭")
        close_btn.setFont(QFont("Microsoft YaHei", 12))
        close_btn.setStyleSheet("""
            QPushButton {
                background-color: #95a5a6;
                color: white;
                border: none;
                border-radius: 8px;
                padding: 12px 20px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #7f8c8d;
            }
        """)
        close_btn.clicked.connect(self.close)
        button_layout.addWidget(close_btn)

        button_layout.addStretch()
        main_layout.addLayout(button_layout)

    def create_info_row(self, label_text, value_text, color):
        """创建信息行"""
        layout = QHBoxLayout()

        # 标签
        label = QLabel(label_text)
        label.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))
        label.setStyleSheet(f"color: {color}; min-width: 80px;")
        layout.addWidget(label)

        # 值
        value = QLabel(value_text)
        value.setFont(QFont("Microsoft YaHei", 14))
        value.setStyleSheet("color: #2c3e50; margin-left: 10px;")
        value.setWordWrap(True)
        layout.addWidget(value)

        layout.addStretch()
        return layout

    def setup_style(self):
        """设置对话框样式"""
        self.setStyleSheet("""
            QDialog {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #f8f9fa, stop:1 #e9ecef);
                border-radius: 15px;
            }
        """)

    def load_car_image(self):
        """加载汽车图片"""
        image_url = self.car_data.get('image_url', '')
        if image_url:
            try:
                from utils.image_loader import image_cache
                # 先检查缓存
                cached_pixmap = image_cache.get_cached_image(image_url, (180, 130))

                if not cached_pixmap.isNull():
                    self.image_label.setPixmap(cached_pixmap)
                else:
                    # 如果没有缓存，显示默认图片
                    self.image_label.setText("🚗\n暂无图片")
            except ImportError:
                self.image_label.setText("🚗\n暂无图片")
        else:
            self.image_label.setText("🚗\n暂无图片")

    def visit_website(self):
        """访问官网"""
        from PyQt5.QtGui import QDesktopServices
        from PyQt5.QtCore import QUrl

        url = self.car_data.get('detail_url', '')
        if url:
            QDesktopServices.openUrl(QUrl(url))


class ModernButton(QPushButton):
    """现代化按钮组件"""
    
    def __init__(self, text, button_type="primary"):
        super().__init__(text)
        self.button_type = button_type
        self.setup_style()
    
    def setup_style(self):
        """设置按钮样式"""
        if self.button_type == "primary":
            style = """
                QPushButton {
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 #4facfe, stop:1 #00f2fe);
                    color: white;
                    border: none;
                    border-radius: 12px;
                    padding: 15px 30px;
                    font-weight: bold;
                    font-size: 16px;
                }
                QPushButton:hover {
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 #43a3f5, stop:1 #00d4e6);
                    transform: translateY(-2px);
                }
                QPushButton:pressed {
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 #3a94e6, stop:1 #00bcd4);
                }
                QPushButton:disabled {
                    background: #bdc3c7;
                    color: #7f8c8d;
                }
            """
        elif self.button_type == "success":
            style = """
                QPushButton {
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 #56ab2f, stop:1 #a8e6cf);
                    color: white;
                    border: none;
                    border-radius: 12px;
                    padding: 15px 30px;
                    font-weight: bold;
                    font-size: 16px;
                }
                QPushButton:hover {
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 #4e9a2a, stop:1 #95d5b2);
                }
                QPushButton:disabled {
                    background: #bdc3c7;
                    color: #7f8c8d;
                }
            """
        elif self.button_type == "danger":
            style = """
                QPushButton {
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 #ff6b6b, stop:1 #ee5a52);
                    color: white;
                    border: none;
                    border-radius: 12px;
                    padding: 15px 30px;
                    font-weight: bold;
                    font-size: 16px;
                }
                QPushButton:hover {
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 #ff5252, stop:1 #e53e3e);
                }
            """
        
        self.setStyleSheet(style)


class ModernCard(QFrame):
    """现代化卡片组件"""
    
    def __init__(self, title="", parent=None):
        super().__init__(parent)
        self.title = title
        self.setup_ui()
        self.setup_style()
    
    def setup_ui(self):
        """设置UI"""
        self.layout = QVBoxLayout(self)
        self.layout.setContentsMargins(20, 20, 20, 20)
        self.layout.setSpacing(15)
        
        if self.title:
            title_label = QLabel(self.title)
            title_label.setFont(QFont("Microsoft YaHei", 16, QFont.Bold))
            title_label.setStyleSheet("color: #2c3e50; margin-bottom: 10px;")
            self.layout.addWidget(title_label)
    
    def setup_style(self):
        """设置样式"""
        self.setStyleSheet("""
            ModernCard {
                background-color: white;
                border: none;
                border-radius: 16px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            }
        """)
        
        # 设置阴影效果
        self.setGraphicsEffect(self.create_shadow_effect())
    
    def create_shadow_effect(self):
        """创建阴影效果"""
        from PyQt5.QtWidgets import QGraphicsDropShadowEffect
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(20)
        shadow.setColor(QColor(0, 0, 0, 60))
        shadow.setOffset(0, 4)
        return shadow


class BeautifulDataFetchThread(QThread):
    """美观版数据获取线程"""
    
    data_fetched = pyqtSignal(list)
    error_occurred = pyqtSignal(str)
    progress_updated = pyqtSignal(int)
    status_updated = pyqtSignal(str)
    
    def __init__(self, car_type: str, page_size: int = 50):
        super().__init__()
        self.car_type = car_type
        self.page_size = page_size
    
    def run(self):
        """线程运行方法"""
        try:
            self.status_updated.emit("正在连接服务器...")
            self.progress_updated.emit(10)
            
            import time
            time.sleep(0.5)
            
            self.status_updated.emit("正在获取数据...")
            self.progress_updated.emit(30)
            
            try:
                from crawler.car_crawler import CarCrawler
                crawler = CarCrawler()
                
                self.status_updated.emit("正在解析数据...")
                self.progress_updated.emit(60)
                
                if self.car_type == "小轿车":
                    cars = crawler.get_sedan_ranking(self.page_size)
                elif self.car_type == "SUV":
                    cars = crawler.get_suv_ranking(self.page_size)
                else:
                    cars = self.create_mock_data()
                
                self.progress_updated.emit(90)
                self.status_updated.emit("数据处理完成")
                self.data_fetched.emit(cars)
                
            except ImportError:
                self.status_updated.emit("使用演示数据...")
                cars = self.create_mock_data()
                self.data_fetched.emit(cars)
            
            self.progress_updated.emit(100)
            
        except Exception as e:
            self.error_occurred.emit(str(e))
    
    def create_mock_data(self):
        """创建精美的模拟数据"""
        mock_cars = []
        car_data = [
            {"name": "比亚迪秦PLUS DM-i", "score": 4.8, "price": "10.58-14.58万", "sales": 35420},
            {"name": "大众朗逸", "score": 4.6, "price": "12.09-15.09万", "sales": 32150},
            {"name": "丰田卡罗拉", "score": 4.7, "price": "11.98-15.98万", "sales": 28960},
            {"name": "本田雅阁", "score": 4.5, "price": "17.98-25.98万", "sales": 25780},
            {"name": "奔驰C级", "score": 4.4, "price": "32.52-37.22万", "sales": 18650},
            {"name": "宝马3系", "score": 4.3, "price": "29.39-40.99万", "sales": 16420},
            {"name": "奥迪A4L", "score": 4.2, "price": "30.58-39.68万", "sales": 14230},
            {"name": "特斯拉Model 3", "score": 4.1, "price": "26.59-34.99万", "sales": 12890},
        ]
        
        for i, data in enumerate(car_data[:self.page_size], 1):
            car_info = {
                'rank': i,
                'name': data['name'],
                'score': data['score'],
                'price': data['price'],
                'sales': data['sales'],
                'image_url': '',
                'detail_url': f'https://www.autohome.com.cn/{1000 + i}',
                'car_id': str(1000 + i)
            }
            mock_cars.append(car_info)
        
        return mock_cars


class EnhancedDataFetchThread(QThread):
    """增强版数据获取线程，支持细化分类"""

    data_fetched = pyqtSignal(list)
    error_occurred = pyqtSignal(str)
    progress_updated = pyqtSignal(int)
    status_updated = pyqtSignal(str)

    def __init__(self, car_type: str, level_id: str, page_size: int = 50):
        super().__init__()
        self.car_type = car_type
        self.level_id = level_id
        self.page_size = page_size

    def run(self):
        """线程运行方法"""
        try:
            self.status_updated.emit("正在连接服务器...")
            self.progress_updated.emit(10)

            import time
            time.sleep(0.5)

            self.status_updated.emit("正在获取数据...")
            self.progress_updated.emit(30)

            try:
                from crawler.car_crawler import CarCrawler
                crawler = CarCrawler()

                self.status_updated.emit("正在解析数据...")
                self.progress_updated.emit(60)

                if self.car_type == "轿车":
                    cars = crawler.get_sedan_ranking(self.page_size, level_id=self.level_id)
                elif self.car_type == "SUV":
                    cars = crawler.get_suv_ranking(self.page_size, level_id=self.level_id)
                elif self.car_type == "MPV":
                    cars = crawler.get_mpv_ranking(self.page_size, level_id=self.level_id)
                else:
                    cars = self.create_mock_data()

                self.progress_updated.emit(90)
                self.status_updated.emit("数据处理完成")
                self.data_fetched.emit(cars)

            except ImportError:
                self.status_updated.emit("使用演示数据...")
                cars = self.create_mock_data()
                self.data_fetched.emit(cars)

            self.progress_updated.emit(100)

        except Exception as e:
            self.error_occurred.emit(str(e))

    def create_mock_data(self):
        """创建模拟数据"""
        mock_cars = []
        car_data = [
            {"name": "比亚迪秦PLUS DM-i", "score": 4.8, "price": "10.58-14.58万", "sales": 35420},
            {"name": "大众朗逸", "score": 4.6, "price": "12.09-15.09万", "sales": 32150},
            {"name": "丰田卡罗拉", "score": 4.7, "price": "11.98-15.98万", "sales": 28960},
            {"name": "本田雅阁", "score": 4.5, "price": "17.98-25.98万", "sales": 25780},
            {"name": "奔驰C级", "score": 4.4, "price": "32.52-37.22万", "sales": 18650},
        ]

        for i, data in enumerate(car_data[:self.page_size], 1):
            car_info = {
                'rank': i,
                'name': f"{data['name']} ({self.car_type})",
                'score': data['score'],
                'price': data['price'],
                'sales': data['sales'],
                'image_url': '',
                'detail_url': f'https://www.autohome.com.cn/{1000 + i}',
                'car_id': str(1000 + i)
            }
            mock_cars.append(car_info)

        return mock_cars


class BeautifulMainWindow(QMainWindow):
    """美观的主窗口类"""
    
    def __init__(self):
        super().__init__()
        self.cars_data = []
        self.fetch_thread = None



        self.setup_ui()
        self.setup_menu()
        self.setup_status_bar()
        self.setup_connections()

        # 设置窗口属性
        self.setWindowTitle("🚗 汽车之家数据分析系统")
        self.setGeometry(100, 100, 1400, 1200)  # 大幅增加默认高度
        self.setMinimumSize(1200, 1000)  # 大幅增加最小高度，确保表格有足够显示空间

        # 设置窗口背景
        self.setup_window_style()

    def get_combo_style(self):
        """获取下拉框样式"""
        return """
            QComboBox {
                background-color: white;
                border: 2px solid #e0e6ed;
                border-radius: 8px;
                padding: 8px 12px;
                font-size: 14px;
                min-width: 100px;
                min-height: 20px;
            }
            QComboBox:focus {
                border-color: #4facfe;
            }
            QComboBox::drop-down {
                border: none;
                width: 25px;
            }
            QComboBox::down-arrow {
                image: none;
                border-left: 5px solid transparent;
                border-right: 5px solid transparent;
                border-top: 5px solid #7f8c8d;
            }
        """

    def setup_window_style(self):
        """设置窗口样式"""
        self.setStyleSheet("""
            QMainWindow {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #667eea, stop:1 #764ba2);
                border-radius: 15px;
            }
            QWidget {
                font-family: "Microsoft YaHei UI", "Segoe UI", sans-serif;
                font-size: 16px;
            }
        """)
    
    def setup_ui(self):
        """设置用户界面"""
        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background-color: transparent;
            }
            QScrollBar:vertical {
                background-color: #f1f3f4;
                width: 12px;
                border-radius: 6px;
            }
            QScrollBar::handle:vertical {
                background-color: #c1c8cd;
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background-color: #a8b2b9;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
            }
        """)

        # 创建可滚动的内容区域
        scroll_content = QWidget()
        scroll_area.setWidget(scroll_content)
        self.setCentralWidget(scroll_area)

        # 主布局
        main_layout = QVBoxLayout(scroll_content)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(20)

        # 标题区域
        self.setup_header(main_layout)

        # 控制面板
        self.setup_control_panel(main_layout)

        # 进度条
        self.setup_progress_bar(main_layout)

        # 数据展示区域
        self.setup_data_display(main_layout)
    
    def setup_header(self, main_layout):
        """设置标题区域"""
        header_card = ModernCard()
        header_layout = QHBoxLayout()
        


        # 标题
        title_label = QLabel("🚗 汽车之家数据分析系统")
        title_label.setFont(QFont("Microsoft YaHei", 28, QFont.Bold))
        title_label.setStyleSheet("""
            color: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 #667eea, stop:1 #764ba2);
            margin: 10px;
        """)
        header_layout.addWidget(title_label)

        # 副标题
        subtitle_label = QLabel("智能汽车数据爬取与可视化分析平台")
        subtitle_label.setFont(QFont("Microsoft YaHei", 14))
        subtitle_label.setStyleSheet("color: #7f8c8d; margin-left: 20px;")
        header_layout.addWidget(subtitle_label)
        
        header_layout.addStretch()
        header_card.layout.addLayout(header_layout)
        main_layout.addWidget(header_card)
    
    def setup_control_panel(self, main_layout):
        """设置控制面板"""
        control_card = ModernCard("🎛️ 数据获取控制")
        control_layout = QGridLayout()
        
        # 汽车类型选择区域
        type_layout = QHBoxLayout()

        # 轿车类型选择
        sedan_label = QLabel("🚗 轿车:")
        sedan_label.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))
        sedan_label.setStyleSheet("color: #34495e; min-width: 60px;")
        type_layout.addWidget(sedan_label)

        self.sedan_combo = QComboBox()
        self.sedan_combo.addItems([
            "全部轿车", "微型车", "小型车", "紧凑型车", "中型车", "中大型车", "大型车"
        ])
        self.sedan_combo.setStyleSheet(self.get_combo_style())
        type_layout.addWidget(self.sedan_combo)

        # 添加轿车搜索按钮
        sedan_search_btn = QPushButton("🔍")
        sedan_search_btn.setFixedSize(30, 30)
        sedan_search_btn.setStyleSheet("""
            QPushButton {
                background-color: #4facfe;
                color: white;
                border: none;
                border-radius: 6px;
                font-weight: bold;
                font-size: 12px;
            }
            QPushButton:hover {
                background-color: #3498db;
            }
        """)
        sedan_search_btn.setToolTip("搜索轿车")
        sedan_search_btn.clicked.connect(lambda: self.auto_fetch_data("轿车", self.sedan_combo.currentText()))
        type_layout.addWidget(sedan_search_btn)

        # SUV类型选择
        suv_label = QLabel("🚙 SUV:")
        suv_label.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))
        suv_label.setStyleSheet("color: #34495e; min-width: 60px; margin-left: 20px;")
        type_layout.addWidget(suv_label)

        self.suv_combo = QComboBox()
        self.suv_combo.addItems([
            "全部SUV", "小型SUV", "紧凑型SUV", "中型SUV", "中大型SUV", "大型SUV"
        ])
        self.suv_combo.setStyleSheet(self.get_combo_style())
        type_layout.addWidget(self.suv_combo)

        # 添加SUV搜索按钮
        suv_search_btn = QPushButton("🔍")
        suv_search_btn.setFixedSize(30, 30)
        suv_search_btn.setStyleSheet("""
            QPushButton {
                background-color: #4facfe;
                color: white;
                border: none;
                border-radius: 6px;
                font-weight: bold;
                font-size: 12px;
            }
            QPushButton:hover {
                background-color: #3498db;
            }
        """)
        suv_search_btn.setToolTip("搜索SUV")
        suv_search_btn.clicked.connect(lambda: self.auto_fetch_data("SUV", self.suv_combo.currentText()))
        type_layout.addWidget(suv_search_btn)

        # MPV类型选择
        mpv_label = QLabel("🚐 MPV:")
        mpv_label.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))
        mpv_label.setStyleSheet("color: #34495e; min-width: 60px; margin-left: 20px;")
        type_layout.addWidget(mpv_label)

        self.mpv_combo = QComboBox()
        self.mpv_combo.addItems(["全部MPV"])
        self.mpv_combo.setStyleSheet(self.get_combo_style())
        type_layout.addWidget(self.mpv_combo)

        # 添加MPV搜索按钮
        mpv_search_btn = QPushButton("🔍")
        mpv_search_btn.setFixedSize(30, 30)
        mpv_search_btn.setStyleSheet("""
            QPushButton {
                background-color: #4facfe;
                color: white;
                border: none;
                border-radius: 6px;
                font-weight: bold;
                font-size: 12px;
            }
            QPushButton:hover {
                background-color: #3498db;
            }
        """)
        mpv_search_btn.setToolTip("搜索MPV")
        mpv_search_btn.clicked.connect(lambda: self.auto_fetch_data("MPV", self.mpv_combo.currentText()))
        type_layout.addWidget(mpv_search_btn)

        type_layout.addStretch()
        control_layout.addLayout(type_layout, 0, 0, 1, 4)

        # 添加使用说明
        tip_label = QLabel("💡 提示：选择车型后点击🔍按钮搜索，或点击下拉框选择不同选项自动搜索")
        tip_label.setFont(QFont("Microsoft YaHei", 10))
        tip_label.setStyleSheet("""
            color: #7f8c8d;
            background-color: #f8f9fa;
            padding: 8px 12px;
            border-radius: 6px;
            border: 1px solid #e9ecef;
        """)
        control_layout.addWidget(tip_label, 1, 0, 1, 2)

        # 数据量选择 - 添加到第二行
        size_layout = QHBoxLayout()
        size_label = QLabel("📊 数据量:")
        size_label.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))
        size_label.setStyleSheet("color: #34495e; min-width: 80px;")
        size_layout.addWidget(size_label)

        self.page_size_spin = QSpinBox()
        self.page_size_spin.setRange(5, 100)
        self.page_size_spin.setValue(20)
        self.page_size_spin.setSuffix(" 条")
        self.page_size_spin.setStyleSheet("""
            QSpinBox {
                background-color: white;
                border: 2px solid #e0e6ed;
                border-radius: 8px;
                padding: 8px 12px;
                font-size: 14px;
                min-width: 100px;
                min-height: 20px;
            }
            QSpinBox:focus {
                border-color: #4facfe;
            }
        """)
        size_layout.addWidget(self.page_size_spin)
        size_layout.addStretch()
        control_layout.addLayout(size_layout, 1, 2, 1, 2)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        self.fetch_btn = ModernButton("🚀 手动获取", "primary")
        self.fetch_btn.setMinimumWidth(120)
        button_layout.addWidget(self.fetch_btn)
        
        self.export_btn = ModernButton("📊 导出数据", "success")
        self.export_btn.setMinimumWidth(120)
        self.export_btn.setEnabled(False)
        button_layout.addWidget(self.export_btn)
        
        self.clear_btn = ModernButton("🗑️ 清空", "danger")
        self.clear_btn.setMinimumWidth(100)
        button_layout.addWidget(self.clear_btn)
        
        button_layout.addStretch()
        control_layout.addLayout(button_layout, 3, 0, 1, 4)
        
        control_card.layout.addLayout(control_layout)
        main_layout.addWidget(control_card)

    def setup_progress_bar(self, main_layout):
        """设置进度条"""
        self.progress_card = ModernCard()
        self.progress_card.setVisible(False)

        progress_layout = QVBoxLayout()

        self.status_label = QLabel("准备中...")
        self.status_label.setFont(QFont("Microsoft YaHei", 10))
        self.status_label.setStyleSheet("color: #7f8c8d; margin-bottom: 8px;")
        progress_layout.addWidget(self.status_label)

        self.progress_bar = QProgressBar()
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                border: none;
                border-radius: 8px;
                background-color: #ecf0f1;
                height: 16px;
                text-align: center;
                font-weight: bold;
                color: white;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #4facfe, stop:1 #00f2fe);
                border-radius: 8px;
            }
        """)
        progress_layout.addWidget(self.progress_bar)

        self.progress_card.layout.addLayout(progress_layout)
        main_layout.addWidget(self.progress_card)

    def setup_data_display(self, main_layout):
        """设置数据展示区域"""
        display_card = ModernCard("📊 数据展示")
        display_card.setMinimumHeight(800)  # 大幅增加最小高度，确保表格有足够显示空间

        # 创建选项卡
        self.tab_widget = QTabWidget()
        self.tab_widget.setMinimumHeight(750)  # 大幅增加选项卡最小高度，确保表格和统计内容都有足够空间
        self.tab_widget.setStyleSheet("""
            QTabWidget::pane {
                border: none;
                background-color: transparent;
            }
            QTabBar::tab {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #f8f9fa, stop:1 #e9ecef);
                border: none;
                border-radius: 8px 8px 0 0;
                padding: 12px 20px;
                margin-right: 4px;
                font-weight: bold;
                color: #495057;
            }
            QTabBar::tab:selected {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #4facfe, stop:1 #00f2fe);
                color: white;
            }
            QTabBar::tab:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #e3f2fd, stop:1 #bbdefb);
            }
        """)

        # 表格视图
        self.setup_table_view()

        # 卡片视图
        self.setup_card_view()

        # 统计视图
        self.setup_stats_view()

        display_card.layout.addWidget(self.tab_widget)
        main_layout.addWidget(display_card)

    def setup_card_view(self):
        """设置卡片视图"""
        # 创建卡片视图的滚动区域
        card_scroll_area = QScrollArea()
        card_scroll_area.setWidgetResizable(True)
        card_scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        card_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        card_scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background-color: #f8f9fa;
            }
        """)

        # 汽车列表组件
        self.car_list_widget = CarListWidget()
        card_scroll_area.setWidget(self.car_list_widget)

        self.tab_widget.addTab(card_scroll_area, "🎴 卡片视图")

    def setup_table_view(self):
        """设置表格视图"""
        table_widget = QWidget()
        table_layout = QVBoxLayout(table_widget)

        # 搜索栏
        search_layout = QHBoxLayout()
        search_label = QLabel("🔍 搜索:")
        search_label.setFont(QFont("Microsoft YaHei", 16, QFont.Bold))
        search_label.setStyleSheet("color: #495057; font-weight: bold;")
        search_layout.addWidget(search_label)

        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入车名搜索...")
        self.search_input.setStyleSheet("""
            QLineEdit {
                background-color: white;
                border: 2px solid #e0e6ed;
                border-radius: 8px;
                padding: 12px 15px;
                font-size: 16px;
                min-height: 20px;
            }
            QLineEdit:focus {
                border-color: #4facfe;
            }
        """)
        # 让搜索框占用更多空间
        search_layout.addWidget(self.search_input, 1)  # 添加拉伸因子

        # 添加清空按钮
        clear_btn = QPushButton("清空")
        clear_btn.setStyleSheet("""
            QPushButton {
                background-color: #6c757d;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 6px;
                font-size: 14px;
                font-weight: bold;
                margin-left: 10px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #5a6268;
            }
        """)
        clear_btn.clicked.connect(lambda: self.search_input.clear())
        search_layout.addWidget(clear_btn, 0)  # 不拉伸，保持固定大小

        table_layout.addLayout(search_layout)

        # 表格
        self.table_widget = QTableWidget()
        self.table_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        # 确保表格有滚动条和足够的最小高度
        self.table_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.table_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.table_widget.setMinimumHeight(500)  # 设置表格最小高度
        columns = ["🏆 排名", "🚗 车名", "⭐ 评分", "💰 价格", "📈 销量", "🔗 详情"]
        self.table_widget.setColumnCount(len(columns))
        self.table_widget.setHorizontalHeaderLabels(columns)

        # 美化表格样式
        self.table_widget.setStyleSheet("""
            QTableWidget {
                gridline-color: #e9ecef;
                background-color: white;
                border: none;
                border-radius: 8px;
                selection-background-color: #e3f2fd;
            }
            QTableWidget::item {
                padding: 15px 10px;
                border-bottom: 1px solid #f1f3f4;
                font-size: 16px;
                min-height: 25px;
            }
            QTableWidget::item:selected {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #4facfe, stop:1 #00f2fe);
                color: white;
            }
            QHeaderView::section {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #667eea, stop:1 #764ba2);
                color: white;
                padding: 15px 10px;
                border: none;
                font-weight: bold;
                font-size: 16px;
            }
            QHeaderView::section:first {
                border-top-left-radius: 8px;
            }
            QHeaderView::section:last {
                border-top-right-radius: 8px;
            }
        """)

        self.table_widget.setAlternatingRowColors(True)
        self.table_widget.setSelectionBehavior(QTableWidget.SelectRows)

        # 设置列宽分布 - 合理分配空间
        header = self.table_widget.horizontalHeader()

        # 设置各列的拉伸模式，合理分配宽度
        header.setSectionResizeMode(0, QHeaderView.Fixed)      # 排名列 - 固定宽度
        header.setSectionResizeMode(1, QHeaderView.Fixed)      # 车名列 - 固定宽度，给足够空间
        header.setSectionResizeMode(2, QHeaderView.Fixed)      # 评分列 - 固定宽度
        header.setSectionResizeMode(3, QHeaderView.Fixed)      # 价格列 - 固定宽度
        header.setSectionResizeMode(4, QHeaderView.Fixed)      # 销量列 - 固定宽度
        header.setSectionResizeMode(5, QHeaderView.Stretch)    # 详情列 - 自动拉伸填充剩余空间

        # 设置合理的列宽
        self.table_widget.setColumnWidth(0, 100)   # 排名列
        self.table_widget.setColumnWidth(1, 250)  # 车名列 - 给足够空间显示车名
        self.table_widget.setColumnWidth(2, 250)  # 评分列 - 显示星级
        self.table_widget.setColumnWidth(3, 250)  # 价格列 - 显示价格范围
        self.table_widget.setColumnWidth(4, 250)  # 销量列 - 显示销量数字

        self.table_widget.verticalHeader().setVisible(False)

        # 添加表格点击事件
        self.table_widget.cellClicked.connect(self.on_table_cell_clicked)

        table_layout.addWidget(self.table_widget, 1)  # 添加拉伸因子
        self.tab_widget.addTab(table_widget, "📋 数据表格")

    def setup_stats_view(self):
        """设置统计视图"""
        stats_widget = QWidget()
        stats_layout = QVBoxLayout(stats_widget)
        stats_layout.setSpacing(20)

        # 统计卡片区域 - 使用水平布局让卡片自适应
        stats_cards_widget = QWidget()
        stats_cards_layout = QHBoxLayout(stats_cards_widget)
        stats_cards_layout.setSpacing(15)

        # 总数统计
        self.total_card = self.create_stat_card("📊 总数据量", "0", "#4facfe")
        stats_cards_layout.addWidget(self.total_card)

        # 平均评分
        self.avg_score_card = self.create_stat_card("⭐ 平均评分", "0.0", "#56ab2f")
        stats_cards_layout.addWidget(self.avg_score_card)

        # 最高销量
        self.max_sales_card = self.create_stat_card("🔥 最高销量", "0", "#ff6b6b")
        stats_cards_layout.addWidget(self.max_sales_card)

        # 价格区间
        self.price_range_card = self.create_stat_card("💰 价格区间", "暂无", "#f39c12")
        stats_cards_layout.addWidget(self.price_range_card)

        stats_layout.addWidget(stats_cards_widget)

        # 详细统计信息
        self.stats_text = QTextEdit()
        self.stats_text.setReadOnly(True)
        self.stats_text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        # 确保滚动条可见
        self.stats_text.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.stats_text.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.stats_text.setStyleSheet("""
            QTextEdit {
                background-color: white;
                border: 2px solid #e0e6ed;
                border-radius: 8px;
                padding: 15px;
                font-family: "Consolas", "Monaco", monospace;
                font-size: 15px;
                line-height: 1.6;
            }
        """)
        self.stats_text.setPlainText("📈 数据统计信息将在获取数据后显示...")

        stats_layout.addWidget(self.stats_text, 1)  # 添加拉伸因子
        self.tab_widget.addTab(stats_widget, "📈 数据统计")

        # 设置AI选项卡
        self.setup_ai_view()

    def create_stat_card(self, title, value, color):
        """创建统计卡片"""
        card = QFrame()
        card.setStyleSheet(f"""
            QFrame {{
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 {color}, stop:1 {color}dd);
                border-radius: 15px;
                border: none;
                min-width: 220px;
                min-height: 70px;
                max-height: 70px;
            }}
        """)

        # 设置大小策略为可扩展
        card.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        layout = QVBoxLayout(card)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setAlignment(Qt.AlignCenter)

        # 创建一个标签来显示完整的文本（标题 + 数值）
        content_label = QLabel(f"{title} {value}")
        content_label.setFont(QFont("Microsoft YaHei", 16, QFont.Bold))
        content_label.setStyleSheet("""
            color: white;
            background: transparent;
            padding: 0px;
            margin: 0px;
        """)
        content_label.setAlignment(Qt.AlignCenter)
        content_label.setWordWrap(False)

        layout.addWidget(content_label)

        # 保存content_label引用以便更新
        card.value_label = content_label
        card.title_text = title  # 保存标题文本用于更新

        return card

    def setup_ai_view(self):
        """设置AI视图"""
        if not AI_AVAILABLE:
            # 如果AI不可用，显示提示信息
            ai_widget = QWidget()
            ai_layout = QVBoxLayout(ai_widget)
            ai_layout.setAlignment(Qt.AlignCenter)

            info_label = QLabel("🤖 AI功能暂不可用")
            info_label.setFont(QFont("Microsoft YaHei", 16, QFont.Bold))
            info_label.setStyleSheet("color: #6c757d; margin: 20px;")
            info_label.setAlignment(Qt.AlignCenter)
            ai_layout.addWidget(info_label)

            desc_label = QLabel("请确保已安装相关依赖包并配置API密钥")
            desc_label.setFont(QFont("Microsoft YaHei", 12))
            desc_label.setStyleSheet("color: #6c757d; margin: 10px;")
            desc_label.setAlignment(Qt.AlignCenter)
            ai_layout.addWidget(desc_label)

            self.tab_widget.addTab(ai_widget, "🤖 AI顾问")
            return

        # 创建AI聊天组件
        try:
            # 使用正确的DeepSeek API密钥
            api_key = "sk-39f586799e5e4cfca2f59ec99aa6e687"
            self.ai_chat_widget = AIChatWidget(api_key, self.cars_data)
            self.tab_widget.addTab(self.ai_chat_widget, "🤖 AI顾问")
        except Exception as e:
            # 如果创建AI组件失败，显示错误信息
            ai_widget = QWidget()
            ai_layout = QVBoxLayout(ai_widget)
            ai_layout.setAlignment(Qt.AlignCenter)

            error_label = QLabel("🤖 AI功能初始化失败")
            error_label.setFont(QFont("Microsoft YaHei", 16, QFont.Bold))
            error_label.setStyleSheet("color: #dc3545; margin: 20px;")
            error_label.setAlignment(Qt.AlignCenter)
            ai_layout.addWidget(error_label)

            error_desc = QLabel(f"错误信息：{str(e)}")
            error_desc.setFont(QFont("Microsoft YaHei", 10))
            error_desc.setStyleSheet("color: #6c757d; margin: 10px;")
            error_desc.setAlignment(Qt.AlignCenter)
            error_desc.setWordWrap(True)
            ai_layout.addWidget(error_desc)

            self.tab_widget.addTab(ai_widget, "🤖 AI顾问")

    def setup_menu(self):
        """设置菜单栏"""
        menubar = self.menuBar()
        menubar.setStyleSheet("""
            QMenuBar {
                background-color: rgba(255, 255, 255, 0.9);
                border: none;
                padding: 4px;
            }
            QMenuBar::item {
                background-color: transparent;
                padding: 8px 12px;
                border-radius: 4px;
            }
            QMenuBar::item:selected {
                background-color: rgba(79, 172, 254, 0.2);
            }
        """)

        # 文件菜单
        file_menu = menubar.addMenu('📁 文件')

        export_action = QAction('📊 导出数据', self)
        export_action.setShortcut('Ctrl+E')
        export_action.triggered.connect(self.export_data)
        file_menu.addAction(export_action)

        file_menu.addSeparator()

        exit_action = QAction('❌ 退出', self)
        exit_action.setShortcut('Ctrl+Q')
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)

        # 工具菜单
        tools_menu = menubar.addMenu('🔧 工具')

        refresh_action = QAction('🔄 刷新数据', self)
        refresh_action.setShortcut('F5')
        refresh_action.triggered.connect(self.fetch_data)
        tools_menu.addAction(refresh_action)

        # 帮助菜单
        help_menu = menubar.addMenu('❓ 帮助')

        about_action = QAction('ℹ️ 关于', self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)

    def setup_status_bar(self):
        """设置状态栏"""
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.setStyleSheet("""
            QStatusBar {
                background-color: rgba(255, 255, 255, 0.9);
                border-top: 1px solid #e0e6ed;
                padding: 5px;
            }
        """)
        self.status_bar.showMessage("🎉 欢迎使用汽车数据分析系统！")

    def setup_connections(self):
        """设置信号连接"""
        self.fetch_btn.clicked.connect(self.fetch_data)
        self.export_btn.clicked.connect(self.export_data)
        self.clear_btn.clicked.connect(self.clear_data)
        self.search_input.textChanged.connect(self.filter_table)

        # 下拉框自动搜索功能
        # 使用activated信号，即使选择相同选项也会触发
        self.sedan_combo.activated[str].connect(self.on_sedan_selection_changed)
        self.suv_combo.activated[str].connect(self.on_suv_selection_changed)
        self.mpv_combo.activated[str].connect(self.on_mpv_selection_changed)

        # 同时保留currentTextChanged信号，用于程序内部改变时的处理
        self.sedan_combo.currentTextChanged.connect(self.on_sedan_text_changed)
        self.suv_combo.currentTextChanged.connect(self.on_suv_text_changed)
        self.mpv_combo.currentTextChanged.connect(self.on_mpv_text_changed)

    def get_selected_car_type(self):
        """获取选择的汽车类型和级别ID"""
        # 检查哪个下拉框被选中（不是默认的"全部"选项）
        sedan_text = self.sedan_combo.currentText()
        suv_text = self.suv_combo.currentText()
        mpv_text = self.mpv_combo.currentText()

        # 汽车类型映射
        car_types = {
            "轿车": {
                "全部轿车": "1,2,3,4,5,6",
                "微型车": "1",
                "小型车": "2",
                "紧凑型车": "3",
                "中型车": "4",
                "中大型车": "5",
                "大型车": "6"
            },
            "SUV": {
                "全部SUV": "16,17,18,19,20",
                "小型SUV": "16",
                "紧凑型SUV": "17",
                "中型SUV": "18",
                "中大型SUV": "19",
                "大型SUV": "20"
            },
            "MPV": {
                "全部MPV": "21,22,23,24"
            }
        }

        # 优先级：MPV > SUV > 轿车（如果多个都不是"全部"，按优先级选择）
        if mpv_text != "全部MPV":
            return "MPV", car_types["MPV"][mpv_text]
        elif suv_text != "全部SUV":
            return "SUV", car_types["SUV"][suv_text]
        elif sedan_text != "全部轿车":
            return "轿车", car_types["轿车"][sedan_text]
        else:
            # 默认返回轿车
            return "轿车", car_types["轿车"]["全部轿车"]

    def on_sedan_selection_changed(self, text):
        """轿车选择变化时的处理（用户点击触发）"""
        print(f"🚗 轿车用户选择: {text}")  # 调试信息

        # 阻止其他下拉框的信号，避免循环触发
        self.suv_combo.blockSignals(True)
        self.mpv_combo.blockSignals(True)

        # 重置其他下拉框为默认值
        self.suv_combo.setCurrentText("全部SUV")
        self.mpv_combo.setCurrentText("全部MPV")

        # 恢复信号
        self.suv_combo.blockSignals(False)
        self.mpv_combo.blockSignals(False)

        # 自动搜索（包括"全部轿车"）
        self.auto_fetch_data("轿车", text)

    def on_suv_selection_changed(self, text):
        """SUV选择变化时的处理（用户点击触发）"""
        print(f"🚙 SUV用户选择: {text}")  # 调试信息

        # 阻止其他下拉框的信号，避免循环触发
        self.sedan_combo.blockSignals(True)
        self.mpv_combo.blockSignals(True)

        # 重置其他下拉框为默认值
        self.sedan_combo.setCurrentText("全部轿车")
        self.mpv_combo.setCurrentText("全部MPV")

        # 恢复信号
        self.sedan_combo.blockSignals(False)
        self.mpv_combo.blockSignals(False)

        # 自动搜索（包括"全部SUV"）
        self.auto_fetch_data("SUV", text)

    def on_mpv_selection_changed(self, text):
        """MPV选择变化时的处理（用户点击触发）"""
        print(f"🚐 MPV用户选择: {text}")  # 调试信息

        # 阻止其他下拉框的信号，避免循环触发
        self.sedan_combo.blockSignals(True)
        self.suv_combo.blockSignals(True)

        # 重置其他下拉框为默认值
        self.sedan_combo.setCurrentText("全部轿车")
        self.suv_combo.setCurrentText("全部SUV")

        # 恢复信号
        self.sedan_combo.blockSignals(False)
        self.suv_combo.blockSignals(False)

        # 自动搜索（包括"全部MPV"）
        self.auto_fetch_data("MPV", text)

    def on_sedan_text_changed(self, text):
        """轿车文本变化时的处理（程序内部调用，不触发搜索）"""
        print(f"🔄 轿车文本变化: {text}")

    def on_suv_text_changed(self, text):
        """SUV文本变化时的处理（程序内部调用，不触发搜索）"""
        print(f"🔄 SUV文本变化: {text}")

    def on_mpv_text_changed(self, text):
        """MPV文本变化时的处理（程序内部调用，不触发搜索）"""
        print(f"🔄 MPV文本变化: {text}")

    def auto_fetch_data(self, car_type, sub_type):
        """自动获取数据"""
        print(f"🔄 自动获取数据: {car_type} - {sub_type}")  # 调试信息

        if self.fetch_thread and self.fetch_thread.isRunning():
            print("⚠️ 数据获取正在进行中，跳过本次请求")  # 调试信息
            return  # 如果正在获取数据，则不执行

        # 获取对应的level_id
        car_types = {
            "轿车": {
                "全部轿车": "1,2,3,4,5,6",
                "微型车": "1",
                "小型车": "2",
                "紧凑型车": "3",
                "中型车": "4",
                "中大型车": "5",
                "大型车": "6"
            },
            "SUV": {
                "全部SUV": "16,17,18,19,20",
                "小型SUV": "16",
                "紧凑型SUV": "17",
                "中型SUV": "18",
                "中大型SUV": "19",
                "大型SUV": "20"
            },
            "MPV": {
                "全部MPV": "21,22,23,24"
            }
        }

        level_id = car_types[car_type][sub_type]
        page_size = self.page_size_spin.value()

        # 清空现有数据
        self.clear_data()

        # 创建并启动数据获取线程
        self.fetch_thread = EnhancedDataFetchThread(car_type, level_id, page_size)
        self.fetch_thread.data_fetched.connect(self.on_data_fetched)
        self.fetch_thread.error_occurred.connect(self.on_error_occurred)
        self.fetch_thread.progress_updated.connect(self.on_progress_updated)
        self.fetch_thread.status_updated.connect(self.on_status_updated)
        self.fetch_thread.finished.connect(self.on_fetch_finished)

        # 更新UI状态
        self.fetch_btn.setEnabled(False)
        self.progress_card.setVisible(True)
        self.progress_bar.setValue(0)
        self.status_bar.showMessage(f"🔄 自动搜索：{car_type}-{sub_type}数据获取中...")

        self.fetch_thread.start()

    def fetch_data(self):
        """获取数据"""
        if self.fetch_thread and self.fetch_thread.isRunning():
            QMessageBox.warning(self, "⚠️ 警告", "数据获取正在进行中，请稍候...")
            return

        # 确定选择的汽车类型和级别
        car_type, level_id = self.get_selected_car_type()
        page_size = self.page_size_spin.value()

        # 清空现有数据
        self.clear_data()

        # 创建并启动数据获取线程
        self.fetch_thread = EnhancedDataFetchThread(car_type, level_id, page_size)
        self.fetch_thread.data_fetched.connect(self.on_data_fetched)
        self.fetch_thread.error_occurred.connect(self.on_error_occurred)
        self.fetch_thread.progress_updated.connect(self.on_progress_updated)
        self.fetch_thread.status_updated.connect(self.on_status_updated)
        self.fetch_thread.finished.connect(self.on_fetch_finished)

        # 更新UI状态
        self.fetch_btn.setEnabled(False)
        self.progress_card.setVisible(True)
        self.progress_bar.setValue(0)
        self.status_bar.showMessage(f"🚀 手动搜索：正在获取{car_type}数据...")

        self.fetch_thread.start()

    def on_data_fetched(self, cars: list):
        """数据获取完成"""
        self.cars_data = cars
        self.update_displays()
        self.export_btn.setEnabled(True)
        self.status_bar.showMessage(f"✅ 成功获取 {len(cars)} 条数据")

        # 更新AI组件的数据
        if AI_AVAILABLE and hasattr(self, 'ai_chat_widget'):
            self.ai_chat_widget.update_cars_data(cars)

    def on_error_occurred(self, error_message: str):
        """发生错误"""
        QMessageBox.critical(self, "❌ 错误", f"数据获取失败:\n{error_message}")
        self.status_bar.showMessage("❌ 数据获取失败")

    def on_progress_updated(self, value: int):
        """进度更新"""
        self.progress_bar.setValue(value)

    def on_status_updated(self, status: str):
        """状态更新"""
        self.status_label.setText(status)

    def on_fetch_finished(self):
        """数据获取完成（无论成功失败）"""
        self.fetch_btn.setEnabled(True)
        self.progress_card.setVisible(False)

    def update_displays(self):
        """更新显示"""
        self.update_card_view()
        self.update_table()
        self.update_stats()

    def update_card_view(self):
        """更新卡片视图"""
        # 清空现有卡片
        self.car_list_widget.clear_cars()

        # 添加新的汽车卡片
        for car in self.cars_data:
            # 将字典数据转换为CarInfo对象（如果需要）
            if isinstance(car, dict):
                # 创建一个简单的CarInfo类来兼容
                class SimpleCarInfo:
                    def __init__(self, data):
                        self.rank = data.get('rank', 0)
                        self.name = data.get('name', '未知')
                        self.score = data.get('score', 0.0)
                        self.price = data.get('price', '暂无报价')
                        self.sales = data.get('sales', 0)
                        self.image_url = data.get('image_url', '')
                        self.detail_url = data.get('detail_url', '')

                car_info = SimpleCarInfo(car)
            else:
                car_info = car

            self.car_list_widget.add_car(car_info)

    def on_table_cell_clicked(self, row, column):
        """处理表格单元格点击事件"""
        # 如果点击的是"查看详情"列（第5列，索引为5）
        if column == 5 and row < len(self.cars_data):
            car_data = self.cars_data[row]

            # 将数据转换为字典格式（如果不是的话）
            if hasattr(car_data, 'rank'):  # CarInfo对象
                car_dict = {
                    'rank': car_data.rank,
                    'name': car_data.name,
                    'score': car_data.score,
                    'price': car_data.price,
                    'sales': car_data.sales,
                    'image_url': getattr(car_data, 'image_url', ''),
                    'detail_url': getattr(car_data, 'detail_url', '')
                }
            else:  # 已经是字典格式
                car_dict = car_data

            # 显示详情对话框
            dialog = CarDetailDialog(car_dict, self)
            dialog.exec_()

    def update_table(self):
        """更新表格"""
        self.table_widget.setRowCount(len(self.cars_data))

        for row, car in enumerate(self.cars_data):
            # 处理不同的数据格式
            if hasattr(car, 'rank'):  # CarInfo对象
                rank, name, score, price, sales, detail_url = (
                    car.rank, car.name, car.score, car.price, car.sales, car.detail_url
                )
            else:  # 字典格式
                rank = car.get('rank', 0)
                name = car.get('name', '未知')
                score = car.get('score', 0.0)
                price = car.get('price', '暂无报价')
                sales = car.get('sales', 0)
                detail_url = car.get('detail_url', '')

            # 排名 - 添加奖牌emoji
            rank_text = str(rank)
            if rank == 1:
                rank_text = "🥇 " + rank_text
            elif rank == 2:
                rank_text = "🥈 " + rank_text
            elif rank == 3:
                rank_text = "🥉 " + rank_text

            rank_item = QTableWidgetItem(rank_text)
            rank_item.setTextAlignment(Qt.AlignCenter)
            self.table_widget.setItem(row, 0, rank_item)

            # 车名
            name_item = QTableWidgetItem(name)
            name_item.setTextAlignment(Qt.AlignCenter)  # 车名居中对齐
            self.table_widget.setItem(row, 1, name_item)

            # 评分 - 添加星级显示
            score_text = f"{score:.1f}"
            if score >= 4.5:
                score_text += " ⭐⭐⭐⭐⭐"
            elif score >= 4.0:
                score_text += " ⭐⭐⭐⭐"
            elif score >= 3.5:
                score_text += " ⭐⭐⭐"
            elif score >= 3.0:
                score_text += " ⭐⭐"
            else:
                score_text += " ⭐"

            score_item = QTableWidgetItem(score_text)
            score_item.setTextAlignment(Qt.AlignCenter)
            self.table_widget.setItem(row, 2, score_item)

            # 价格
            price_item = QTableWidgetItem(str(price))
            price_item.setTextAlignment(Qt.AlignCenter)  # 价格居中对齐
            self.table_widget.setItem(row, 3, price_item)

            # 销量 - 添加火热程度
            sales_text = f"{sales:,}"
            if sales > 30000:
                sales_text += " 🔥🔥🔥"
            elif sales > 20000:
                sales_text += " 🔥🔥"
            elif sales > 10000:
                sales_text += " 🔥"

            sales_item = QTableWidgetItem(sales_text)
            sales_item.setTextAlignment(Qt.AlignCenter)  # 销量居中对齐
            self.table_widget.setItem(row, 4, sales_item)

            # 详情链接
            url_item = QTableWidgetItem("🔗 查看详情")
            url_item.setTextAlignment(Qt.AlignCenter)  # 详情链接居中对齐
            self.table_widget.setItem(row, 5, url_item)

    def update_stats(self):
        """更新统计信息"""
        if not self.cars_data:
            return

        # 计算统计数据
        total_count = len(self.cars_data)
        scores = []
        sales_list = []
        prices = []

        for car in self.cars_data:
            if hasattr(car, 'score'):
                scores.append(car.score)
                sales_list.append(car.sales)
            else:
                scores.append(car.get('score', 0.0))
                sales_list.append(car.get('sales', 0))

        avg_score = sum(scores) / len(scores) if scores else 0
        max_sales = max(sales_list) if sales_list else 0

        # 更新统计卡片
        self.total_card.value_label.setText(f"{self.total_card.title_text} {total_count}")
        self.avg_score_card.value_label.setText(f"{self.avg_score_card.title_text} {avg_score:.1f}")
        self.max_sales_card.value_label.setText(f"{self.max_sales_card.title_text} {max_sales:,}")
        self.price_range_card.value_label.setText(f"{self.price_range_card.title_text} 5-50万")

        # 更新详细统计
        stats_text = f"""
📊 数据统计报告
{'='*50}

📈 基础统计:
   • 总数据量: {total_count} 条
   • 平均评分: {avg_score:.2f} 分
   • 最高销量: {max_sales:,} 辆
   • 最低销量: {min(sales_list) if sales_list else 0:,} 辆

🏆 排名分析:
   • 前三名车型评分均值: {sum(scores[:3])/3 if len(scores) >= 3 else 0:.2f}
   • 销量超过2万的车型: {len([s for s in sales_list if s > 20000])} 款
   • 评分4.5以上的车型: {len([s for s in scores if s >= 4.5])} 款

📊 数据分布:
   • 评分分布: 最高 {max(scores) if scores else 0:.1f}, 最低 {min(scores) if scores else 0:.1f}
   • 销量分布: 最高 {max(sales_list) if sales_list else 0:,}, 最低 {min(sales_list) if sales_list else 0:,}

🔥 热门车型 (销量前3):
"""

        # 添加热门车型信息
        sorted_cars = sorted(self.cars_data,
                           key=lambda x: x.get('sales', 0) if isinstance(x, dict) else x.sales,
                           reverse=True)

        for i, car in enumerate(sorted_cars[:3], 1):
            if hasattr(car, 'name'):
                name, sales = car.name, car.sales
            else:
                name, sales = car.get('name', '未知'), car.get('sales', 0)
            stats_text += f"   {i}. {name}: {sales:,} 辆\n"

        self.stats_text.setPlainText(stats_text)

    def filter_table(self):
        """过滤表格数据"""
        search_text = self.search_input.text().lower()

        for row in range(self.table_widget.rowCount()):
            item = self.table_widget.item(row, 1)  # 车名列
            if item:
                should_show = search_text in item.text().lower()
                self.table_widget.setRowHidden(row, not should_show)

    def clear_data(self):
        """清空数据"""
        self.cars_data.clear()

        # 清空卡片视图
        self.car_list_widget.clear_cars()

        # 清空表格视图
        self.table_widget.setRowCount(0)

        # 清空统计信息
        self.stats_text.setPlainText("📈 数据统计信息将在获取数据后显示...")
        self.export_btn.setEnabled(False)

        # 重置统计卡片
        self.total_card.value_label.setText("0")
        self.avg_score_card.value_label.setText("0.0")
        self.max_sales_card.value_label.setText("0")
        self.price_range_card.value_label.setText("暂无")

    def export_data(self):
        """导出数据"""
        if not self.cars_data:
            QMessageBox.warning(self, "⚠️ 警告", "没有数据可导出")
            return

        # 获取当前选择的汽车类型
        car_type, _ = self.get_selected_car_type()

        # 生成默认文件名
        from datetime import datetime
        current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
        default_filename = f"汽车数据_{car_type}_{current_time}"

        # 获取用户的文档目录作为默认路径
        import os
        default_dir = os.path.expanduser("~/Documents")
        if not os.path.exists(default_dir):
            default_dir = os.path.expanduser("~")

        default_path = os.path.join(default_dir, default_filename)

        # 显示文件保存对话框
        file_path, selected_filter = QFileDialog.getSaveFileName(
            self,
            "📊 导出汽车数据",
            default_path,
            "Excel文件 (*.xlsx);;CSV文件 (*.csv);;文本文件 (*.txt);;所有文件 (*.*)"
        )

        if not file_path:
            return

        try:
            # 根据文件扩展名选择导出格式
            if file_path.lower().endswith('.xlsx'):
                self._export_to_excel(file_path, car_type)
            elif file_path.lower().endswith('.csv'):
                self._export_to_csv(file_path, car_type)
            else:
                self._export_to_txt(file_path, car_type)

            QMessageBox.information(self, "✅ 成功", f"数据已成功导出到:\n{file_path}")

        except Exception as e:
            QMessageBox.critical(self, "❌ 错误", f"导出失败:\n{str(e)}")

    def _export_to_excel(self, file_path: str, car_type: str):
        """导出到Excel文件"""
        try:
            import pandas as pd

            # 准备数据
            data = []
            for car in self.cars_data:
                if hasattr(car, 'rank'):  # CarInfo对象
                    row = {
                        '排名': car.rank,
                        '车名': car.name,
                        '评分': car.score,
                        '价格': car.price,
                        '销量': car.sales,
                        '详情链接': getattr(car, 'detail_url', '')
                    }
                else:  # 字典格式
                    row = {
                        '排名': car.get('rank', ''),
                        '车名': car.get('name', ''),
                        '评分': car.get('score', ''),
                        '价格': car.get('price', ''),
                        '销量': car.get('sales', ''),
                        '详情链接': car.get('detail_url', '')
                    }
                data.append(row)

            # 创建DataFrame并导出
            df = pd.DataFrame(data)

            # 使用ExcelWriter添加格式
            with pd.ExcelWriter(file_path, engine='openpyxl') as writer:
                df.to_excel(writer, sheet_name=f'{car_type}数据', index=False)

                # 获取工作表并美化格式
                worksheet = writer.sheets[f'{car_type}数据']

                # 设置列宽
                column_widths = {
                    'A': 8,   # 排名
                    'B': 25,  # 车名
                    'C': 12,  # 评分
                    'D': 20,  # 价格
                    'E': 15,  # 销量
                    'F': 30   # 详情链接
                }

                for col_letter, width in column_widths.items():
                    worksheet.column_dimensions[col_letter].width = width

                # 设置表头样式
                from openpyxl.styles import Font, PatternFill, Alignment
                header_font = Font(bold=True, color="FFFFFF")
                header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
                header_alignment = Alignment(horizontal="center", vertical="center")

                for cell in worksheet[1]:
                    cell.font = header_font
                    cell.fill = header_fill
                    cell.alignment = header_alignment

                # 设置数据行样式
                data_alignment = Alignment(horizontal="center", vertical="center")
                for row in worksheet.iter_rows(min_row=2, max_row=worksheet.max_row):
                    for cell in row:
                        cell.alignment = data_alignment

        except ImportError:
            # 如果没有pandas，使用CSV格式
            QMessageBox.warning(self, "⚠️ 提示", "未安装pandas库，将以CSV格式导出")
            self._export_to_csv(file_path.replace('.xlsx', '.csv'), car_type)

    def _export_to_csv(self, file_path: str, car_type: str):
        """导出到CSV文件"""
        import csv
        from datetime import datetime

        with open(file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
            writer = csv.writer(csvfile)

            # 写入标题信息
            writer.writerow([f'🚗 {car_type}数据导出报告'])
            writer.writerow([f'导出时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}'])
            writer.writerow([f'数据总数: {len(self.cars_data)} 条'])
            writer.writerow([])  # 空行

            # 写入表头
            writer.writerow(['排名', '车名', '评分', '价格', '销量', '详情链接'])

            # 写入数据
            for car in self.cars_data:
                if hasattr(car, 'rank'):  # CarInfo对象
                    row = [
                        car.rank,
                        car.name,
                        car.score,
                        car.price,
                        car.sales,
                        getattr(car, 'detail_url', '')
                    ]
                else:  # 字典格式
                    row = [
                        car.get('rank', ''),
                        car.get('name', ''),
                        car.get('score', ''),
                        car.get('price', ''),
                        car.get('sales', ''),
                        car.get('detail_url', '')
                    ]
                writer.writerow(row)

    def _export_to_txt(self, file_path: str, car_type: str):
        """导出到文本文件"""
        from datetime import datetime

        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(f"🚗 {car_type}数据导出报告\n")
            f.write(f"导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"数据总数: {len(self.cars_data)} 条\n")
            f.write("="*80 + "\n\n")

            for i, car in enumerate(self.cars_data, 1):
                if hasattr(car, 'rank'):
                    f.write(f"{i}. {car.name}\n")
                    f.write(f"   🏆 排名: {car.rank}\n")
                    f.write(f"   ⭐ 评分: {car.score:.1f}\n")
                    f.write(f"   💰 价格: {car.price}\n")
                    f.write(f"   📈 销量: {car.sales:,}\n")
                    if hasattr(car, 'detail_url'):
                        f.write(f"   🔗 详情: {car.detail_url}\n")
                else:
                    f.write(f"{i}. {car.get('name', '未知')}\n")
                    f.write(f"   🏆 排名: {car.get('rank', 0)}\n")
                    f.write(f"   ⭐ 评分: {car.get('score', 0.0):.1f}\n")
                    f.write(f"   💰 价格: {car.get('price', '暂无报价')}\n")
                    f.write(f"   📈 销量: {car.get('sales', 0):,}\n")
                    f.write(f"   🔗 详情: {car.get('detail_url', '')}\n")
                f.write("\n")

    def show_about(self):
        """显示关于对话框"""
        about_text = """
        <div style='text-align: center;'>
        <h2>🚗 汽车之家数据分析系统</h2>
        <p><b>版本:</b> 2.3 AI智能版</p>
        <br>
        <p><b>✨ 主要功能:</b></p>
        <ul style='text-align: left;'>
        <li>🔍 智能数据爬取</li>
        <li>📊 可视化数据展示</li>
        <li>📈 实时统计分析</li>
        <li>🔎 快速搜索过滤</li>
        <li>📋 数据导出功能</li>
        <li>🎨 现代化UI设计</li>
        </ul>
        <br>
        <p><b>🛠️ 技术栈:</b> PyQt5, requests, 现代化CSS</p>
        <p><b>🎯 设计理念:</b> 简洁、美观、高效</p>
        </div>
        """
        QMessageBox.about(self, "ℹ️ 关于系统", about_text)



    def closeEvent(self, event):
        """窗口关闭事件"""
        if self.fetch_thread and self.fetch_thread.isRunning():
            self.fetch_thread.quit()
            self.fetch_thread.wait()
        event.accept()
